package com.huilian.iotbox.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.dao.OrderItemDao;
import com.huilian.iotbox.admin.service.OrderItemService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.OrderDto;
import com.huilian.iotbox.data.enums.DeviceTypeEnum;
import com.huilian.iotbox.data.enums.OrderItemShipmentStatusEnum;
import com.huilian.iotbox.data.enums.OrderItemStatusEnum;
import com.huilian.iotbox.data.properties.ConfigProperties;
import com.huilian.iotbox.data.properties.FileProperties;
import com.huilian.iotbox.data.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * @author LinYinDong
 * @date 2023/12/21 16:15
 */
@Service
@Slf4j
public class OrderItemServiceImpl implements OrderItemService {

    @Resource
    private OrderItemDao orderItemDao;
    @Autowired
    private FileProperties fileProperties;
    @Autowired
    private ConfigProperties configProperties;
    @Override
    public PageInfo findOrderItemList(OrderDto orderDto) {
        orderDto.setDeviceTypeIdArray(new Integer[]{
                DeviceTypeEnum.VENDING_MACHINE.getCode(),
                DeviceTypeEnum.SCREEN_VENDING_MACHINE.getCode(),
                DeviceTypeEnum.OPEN_DOOR_VENDING_MACHINE.getCode()
        });
        PageHelper.startPage(orderDto.getPageNum(), orderDto.getPageSize(), false);
        PageHelper.orderBy("oi.createTime DESC");
        List<OrderVo> orderList = orderItemDao.findOrderItemList(orderDto);
        PageInfo pagResult = new PageInfo(orderList);
        if (orderList.size() < 10) {
            pagResult.setTotal(orderDto.getPageSize() * orderDto.getPageNum());
        } else {
            pagResult.setTotal(orderDto.getPageSize() * orderDto.getPageNum() + 1);
        }
        return pagResult;
    }

    @Override
    public void delete(String endTime) {
        orderItemDao.delete(endTime);
    }

    @Override
    public ServerResponse exportOrderItemList(OrderDto orderDto) {
        orderDto.setDeviceTypeIdArray(new Integer[]{
                DeviceTypeEnum.VENDING_MACHINE.getCode(),
                DeviceTypeEnum.SCREEN_VENDING_MACHINE.getCode(),
                DeviceTypeEnum.OPEN_DOOR_VENDING_MACHINE.getCode()
        });
        List<OrderVo> list = orderItemDao.findOrderItemList(orderDto);
        if(StringUtils.isEmpty(list) || list.size() == 0){
            return ServerResponse.createByErrorMessage("没有数据，可以导出");
        }
        String[] headers = new String[]{"订单号", "场地", "设备号","数量", "商品名称","订单金额","出货货道","出货状态","订单状态","运营商","时间"};
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区为东八区
        // 格式化日期
        String formattedCreateTime = sdf.format(orderDto.getCreateTime());
        String formattedUpdateTime = sdf.format(orderDto.getUpdateTime());
        String sheetName = "出货记录" + formattedCreateTime + "至" + formattedUpdateTime;
        // 创建了一个excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(10);
        sheet.setColumnWidth(0, 30 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(8, 25 * 256);
//        sheet.createFreezePane(0, 4, 0, 4);
        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font font = wb.createFont();
        //设置字体样式
        //font.setFontHeightInPoints((short) 20);   //--->设置字体大小
        font.setFontName("Courier New");   //---》设置字体，是什么类型例如：宋体
        font.setItalic(true);     //--->设置是否是加粗
        titleStyle.setFont(font);     //--->将字体格式加入到style1中
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直

        //内容样式
        HSSFCellStyle contextStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font contextfont = wb.createFont();
        contextfont.setFontHeightInPoints((short) 13);   //--->设置字体大小
        //设置字体样式
        contextStyle.setFont(contextfont);     //--->将字体格式加入到style1中
        contextStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        contextStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直
        contextStyle.setWrapText(true);//设置自动换行

        //表格第一行
        HSSFRow row1 = sheet.createRow(0);   //--->创建一行
        row1.setHeightInPoints(20);
        HSSFCell cell1 = row1.createCell(0);   //--->创建一个单元格
        // cell1.setCellStyle(titleStyle);
        cell1.setCellValue("出货记录");
        //表格第二行
        HSSFRow r2 = sheet.createRow(1);
        r2.setHeightInPoints(20);
        HSSFCell c2 = r2.createCell(0);
        c2.setCellValue("起始时间：[" + sdf.format(orderDto.getCreateTime()) + "]  " + "  终止时间：[" + sdf.format(orderDto.getUpdateTime()) + "]");

        //标题
        HSSFRow row2 = sheet.createRow(3);           //--->创建一行
        contextStyle.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);// 设置背景色
        contextStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        contextStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        contextStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        contextStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        contextStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        contextfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
        contextStyle.setFont(contextfont);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell2 = row2.createCell(i);
            cell2.setCellValue(headers[i]);
            cell2.setCellStyle(contextStyle);
        }
        int index = 0;//记录额外创建的sheet数量
        int j = 0;
        // 循环每行
        for (int i = 4; i < list.size() + 4; i++) {
            if ((i) % 65500 == 0) {
                sheet = wb.createSheet("salesList" + index);
                index++;
            }
            // 创建行
            HSSFRow row = sheet.createRow((i) - (index * 65500));

            //订单号
            HSSFCell contextCell0 = row.createCell(0);
            if (!StringUtils.isEmpty(list.get(j).getOutTradeNo())) {
                contextCell0.setCellValue(list.get(j).getOutTradeNo());
            } else {
                contextCell0.setCellValue("无");
            }
            //场地名称
            HSSFCell contextCell1 = row.createCell(1);
            if (!StringUtils.isEmpty(list.get(j).getStoreName())) {
                contextCell1.setCellValue(list.get(j).getStoreName());
            } else {
                contextCell1.setCellValue("无");
            }
            //设备号
            HSSFCell contextCell2 = row.createCell(2);
            if (!StringUtils.isEmpty(list.get(j).getDeviceNo())) {
                contextCell2.setCellValue(list.get(j).getDeviceNo());
            } else {
                contextCell2.setCellValue("无");
            }
            //数量
            HSSFCell contextCell3 = row.createCell(3);
            if (!StringUtils.isEmpty(list.get(j).getNum())) {
                contextCell3.setCellValue(list.get(j).getNum());
            } else {
                contextCell3.setCellValue("无");
            }
            //商品名称
            HSSFCell contextCell4 = row.createCell(4);
            if (!StringUtils.isEmpty(list.get(j).getCommodityName())) {
                contextCell4.setCellValue(list.get(j).getCommodityName());
            } else {
                contextCell4.setCellValue("无");
            }
            //订单金额
            HSSFCell contextCell5 = row.createCell(5);
            if (!StringUtils.isEmpty(list.get(j).getTotalPrice())) {
                contextCell5.setCellValue(list.get(j).getTotalPrice().toString());
            } else {
                contextCell5.setCellValue("无");
            }
            //出礼货道
            HSSFCell contextCell6 = row.createCell(6);
            if (!StringUtils.isEmpty(list.get(j).getHierarchy()) && !StringUtils.isEmpty(list.get(j).getFreightLane())) {
                contextCell6.setCellValue(list.get(j).getHierarchy()+"层,"+list.get(j).getFreightLane()+"货道");
            } else {
                contextCell6.setCellValue("无");
            }
            //出货状态
            HSSFCell contextCell7 = row.createCell(7);
            if (!StringUtils.isEmpty(list.get(j).getShipmentStatus())) {
                String orderItemShipmentStatusDesc = OrderItemShipmentStatusEnum.getOrderItemShipmentStatusDesc(list.get(j).getShipmentStatus());
                contextCell7.setCellValue(orderItemShipmentStatusDesc);
            } else {
                contextCell7.setCellValue("无");
            }
            //订单状态
            HSSFCell contextCell8 = row.createCell(8);
            if (!StringUtils.isEmpty(list.get(j).getStatus())) {
                String statusName = OrderItemStatusEnum.formatDesc(list.get(j).getStatus());
                contextCell8.setCellValue(statusName);
            } else {
                contextCell8.setCellValue("无");
            }
            //运营商
            HSSFCell contextCell9 = row.createCell(9);
            if (!StringUtils.isEmpty(list.get(j).getName())) {
                contextCell9.setCellValue(list.get(j).getName());
            } else {
                contextCell9.setCellValue("无");
            }
            //时间
            HSSFCell contextCell10 = row.createCell(10);
            contextCell10.setCellValue(sdf.format(list.get(j).getCreateTime())
            );
            j++;
            if (j >= list.size()) {
                j = 0;
            }
        }
        // 保存文件
        FileOutputStream fileOut = null;
        String fileName = fileProperties.getSaveImgPath() + "/" + sheetName + ".xls";

        try {
            File f = new File(fileName);
            if (!f.exists()) {
                f.createNewFile();
            }
            // 文件保存的地址和名称
            log.info("------------------------------iot后台库存记录导出:" + fileName);
            fileOut = new FileOutputStream(fileName);
            wb.write(fileOut);

        } catch (IOException e) {
            // 处理文件操作可能发生的IO异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存失败:" + e + fileProperties.getSaveImgPath());
        } catch (Exception e) {
            // 其他异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存过程中发生了错误:" + e);

        } finally {
            // 关闭流
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Map<String, String> map = new HashMap<>();
        map.put("fileName", sheetName + ".xls");
        map.put("downloadUrl",configProperties.getAdminBackEndUrl() + "/api/fileExport/download/" +sheetName + ".xls");
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public List<OrderVo> findListByOrderId(OrderDto orderDto) {
        return orderItemDao.findListByOrderId(orderDto);
    }
}
